<?php
$userName = trim($_POST['userName']);
$pwd = trim($_POST['pwd']);
$cpwd = trim($_POST['cpwd']);
$sex = trim($_POST['sex']);
$fav = @implode(",", $_POST['fav']);
$email = trim($_POST['email']);

// 进行必要的验证
if (!strlen($userName)) {
    echo "<script>alert('用户名没有填写');history.back();</script>";
    exit;
} elseif (!preg_match('/^[a-zA-Z0-9]{3,10}$/', $userName)) {
    echo "<script>alert('用户名必填，且只能由大小写字符和数字组成，长度在3到10个字符!');history.back();</script>";
    exit;
}

if (!empty($pwd)) {
    if ($pwd <> $cpwd) {
        echo "<script>alert('密码和确认密码必须相同');history.back();</script>";
        exit;
    } elseif (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/', $pwd)) {
        echo "<script>alert('密码必填,且只能大小写和数字,以及*_构成,长度为6到10个字符!');history.back();</script>";
        exit;
    }
}

if (!empty($email)) {
    if (!preg_match("/^[a-zA-Z0-9_\-]+@[a-zA-Z0-9]+\.(com|cn|net|org)$/", $email)) {
        echo "<script>alert('信箱格式不正确!');history.back();</script>";
        exit;
    }
}

include_once 'conn.php';
if (!empty($pwd)) { // 说明要更新密码
    $sql = "update user set pwd='" . md5($pwd) . "',email='$email',sex='$sex',fav='$fav' where userName='$userName'";
} else {
    $sql = "update user set email='$email',sex='$sex',fav='$fav' where userName='$userName'";
}

$result = mysqli_query($conn, $sql);
if ($result) {
    echo "<script>alert('更新个人资料成功');location.href='index.php';</script>";
}else{
    echo "<script>alert('更新个人资料失败!');history.back()</script>";
}